<script setup lang="ts">
import { onMounted, ref } from "vue";
import { cmd } from "./utils/cmdClient";
import { network } from "./utils/network";

const host: string = "127.0.0.1"

const port: number = 4001

const infoLabel = ref('')

const pongLabel = ref('')

const start = () => {
  console.info('start')
  network.onOpen(svr_onOpen, this);
  network.onClose(svr_onClose, this);
  connectSvr();
}

onMounted(() => {
  setInterval(() => {
    network.readMsg();
  }, 100)
})

const connectSvr = () => {
  infoLabel.value = "连接服务器中..."
  network.connect(host, port);
}

const svr_onOpen = () => {
  console.log("socket onopen");
  infoLabel.value = "服务器已连接"
  network.addHandler(cmd.connector_main_ping, svr_pingBack, this);
}

const svr_onClose = () => {
  console.log("socket onclose");
  infoLabel.value = "连接服务器中..."
  setTimeout(() => {
    connectSvr();
  }, 2000)
}

const btn_ping = () => {
  network.sendMsg(cmd.connector_main_ping, { "msg": "ping" });
}

const svr_pingBack = (msg: { "msg": string }) => {
  pongLabel.value = msg.msg;
}
</script>

<template>
  <div>
    <div>InfoLabel: {{ infoLabel }}</div>
    <div>PongLabel: {{ pongLabel }}</div>
    <button @click="start"> 开始</button>
    <button @click="btn_ping"> Ping</button>
  </div>
</template>

<style scoped></style>
